package com.ruoyi.event.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * redis 键过期监听器
 * MessageListener通过侦听密钥过期的Redis密钥空间通知，
 * 通过ApplicationEventPublisher发布RedisKeyExpiredEvent。
 *
 * @author xueyu
 */
@Slf4j
@Component
public class MyRedisKeyExpirationEventMessageListener extends KeyExpirationEventMessageListener {

    @Autowired
    public MyRedisKeyExpirationEventMessageListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * @param message 消息
     * @param pattern pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        String channelStr = new String(channel, StandardCharsets.UTF_8);
        RedisKeyExpiredEvent<Object> event = new RedisKeyExpiredEvent<>(channelStr, body, null);
        publishEvent(event);
    }
}
